<script setup lang="ts">
import dayjs from 'dayjs'
import type { PolluteErrRow } from '@/api/modules/types/data.query'
import dataQueryApi from '@/api/modules/data.query'
import useKeepAliveStore from '@/store/modules/keepAlive'
import { repaceUrl } from '@/utils'

const keepAliveStore = useKeepAliveStore()

onBeforeRouteLeave((to) => {
  if (to.name !== 'data-real-time-list') {
    keepAliveStore.remove('DataRealTimeList')
  }
})
const route = useRoute()
const deviceInfo: PolluteErrRow = JSON.parse(sessionStorage.getItem('PolluteErrRow') || '{}')
const deviceId = ref(route.params.id as string)
const column = [
  { field: 'Time', title: '时间', fixed: 'left', width: 120 },
  {
    field: 'dy',
    title: '电压',
    children: [
      { field: '11', title: 'A相', width: 120 },
      { field: '12', title: 'B相', width: 120 },
      { field: '13', title: 'C相', width: 120 },
    ],
    emptyString: '--',
  },
  {
    field: 'dl',
    title: '电流',
    children: [
      { field: '21', title: 'A相', width: 120 },
      { field: '22', title: 'B相', width: 120 },
      { field: '23', title: 'C相', width: 120 },
    ],
    emptyString: '--',
  },
  {
    field: 'gl',
    title: '功率',
    children: [
      { field: '500', title: '总有功', width: 120 },
      { field: '501', title: 'A相', width: 120 },
      { field: '502', title: 'B相', width: 120 },
      { field: '503', title: 'C相', width: 120 },
    ],
    emptyString: '--',
  },
  {
    field: 'glys',
    title: '功率因数',
    children: [
      { field: '40', title: '总', width: 120 },
      { field: '41', title: 'A相', width: 120 },
      { field: '42', title: 'B相', width: 120 },
      { field: '43', title: 'C相', width: 120 },
    ],
    emptyString: '--',
  },
  {
    field: 'dyxwj',
    title: '电压相位角',
    children: [
      { field: '311', title: 'A相', width: 120 },
      { field: '312', title: 'B相', width: 120 },
      { field: '313', title: 'C相', width: 120 },
    ],
    emptyString: '--',
  },
  {
    field: 'dlxwj',
    title: '电流相位角',
    children: [
      { field: '321', title: 'A相', width: 120 },
      { field: '322', title: 'B相', width: 120 },
      { field: '323', title: 'C相', width: 120 },
    ],
    emptyString: '--',
  },
  {
    field: 'sz',
    title: '示值',
    children: [
      { field: '7000', title: '正向有功', width: 120 },
      { field: '7010', title: '正向无功', width: 120 },
      { field: '7100', title: '反向有功', width: 120 },
      { field: '7110', title: '反向无功', width: 120 },
    ],
    emptyString: '--',
  },
  {
    field: 'dl2',
    title: '电量',
    children: [
      { field: '8000', title: '正向有功', width: 120 },
      { field: '8010', title: '正向无功', width: 120 },
      { field: '8100', title: '反向有功', width: 120 },
      { field: '8110', title: '反向无功', width: 120 },
    ],
    emptyString: '--',
  },
  {
    field: 'wd',
    title: '温度',
    children: [
      { field: '91', title: 'A相', width: 120 },
      { field: '92', title: 'B相', width: 120 },
      { field: '93', title: 'C相', width: 120 },
    ],
    emptyString: '--',
  },
  {
    field: 'UpdateTime',
    title: '更新时间',
    width: 180,
    emptyString: '--',
  },
]
const gridOptions: any = reactive({
  'border': true,
  'height': '100%',
  'autoResize': true,
  'columnConfig': {
    resizable: true,
  },
  'show-overflow': true,
  'loading': false,
  'columns': column,
  'data': [],
  'rowConfig': {
    isCurrent: true,
  },
  'scroll-y': {
    enabled: true,
    gt: 30,
  },
})

function currentChange(val: any) {
  if (val.ObjID) {
    repaceUrl(`/data-query/real-time/electric/${val.ObjID}`)
    deviceId.value = val.ObjID
    getErrorData()
  }
}
const currentTime = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))

const markerIDs = computed(() => {
  const ids: any[] = []
  column.forEach((item) => {
    if (item.children) {
      item.children.forEach((child) => {
        ids.push(Number(child.field))
      })
    }
  })
  return ids
})

const startTime = computed(() => {
  return dayjs(currentTime.value).format('YYYY-MM-DD')
})
const endTime = computed(() => {
  return dayjs(currentTime.value).add(1, 'day').format('YYYY-MM-DD')
})

function changeDay(type: string) {
  if (type === 'next') {
    currentTime.value = dayjs(currentTime.value).add(1, 'day').format('YYYY-MM-DD HH:mm:ss')
  }
  else {
    currentTime.value = dayjs(currentTime.value).subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss')
  }
  getErrorData()
}
const tableRef = ref()

function getErrorData() {
  gridOptions.loading = true
  dataQueryApi.GetElectricTS({
    deviceObjIDs: [deviceId.value],
    markerIDs: markerIDs.value,
    startTime: startTime.value,
    endTime: endTime.value,
  }).then((res) => {
    const { Columns, Datas, UpdateTimes } = res as any
    const timeLine = Columns
    const datas = Datas[deviceId.value]
    const currentUpdateTime = UpdateTimes[deviceId.value]
    let tempRow: any = null
    const nowData = dayjs()
    gridOptions.data = timeLine.map((item: any, index: number) => {
      const row: any = {
        Time: item.substring(11),
        UpdateTime: currentUpdateTime ? currentUpdateTime[index] : '',
      }
      datas && markerIDs.value.forEach((id) => {
        const value = datas[id][index] === null ? '--' : datas[id][index]
        row[String(id)] = value
      })
      if (nowData.isAfter(dayjs(item)) && nowData.add(15, 'minute').isAfter(dayjs(item))) {
        tempRow = row
      }
      return row
    })
    gridOptions.loading = false
    if (tempRow) {
      setTimeout(() => {
        tableRef.value.setCurrentRow(tempRow).then(() => {
          const row = tableRef.value.getCurrentRecord()
          tableRef.value.scrollToRow(row)
        })
      }, 500)
    }
  }, () => {
    gridOptions.loading = false
  })
}

function changeTime(value: any) {
  currentTime.value = value
  getErrorData()
}

getErrorData()
</script>

<template>
  <PageMain>
    <div class="w-full flex">
      <div class="mr-20px w-300px flex-shrink-0 b-r-1px b-r-#EBEEF5 b-r-solid pr-10px">
        <EntDeviceTree :ent-id="deviceInfo.EntObjID" :device-id="deviceId" @current-change="currentChange" />
      </div>
      <div class="flex-grow-1 overflow-x-hidden">
        <div class="mb-10px">
          <el-date-picker v-model="currentTime" type="date" value-format="YYYY-MM-DD HH:mm:ss" @change="changeTime" />
          <el-button-group class="ml-10px">
            <el-button type="primary" @click="changeDay('prev')">
              前一天
            </el-button>
            <el-button type="primary" @click="changeDay('next')">
              后一天
            </el-button>
          </el-button-group>
        </div>
        <div v-auto-height="85" class="w-full">
          <vxe-grid ref="tableRef" v-bind="gridOptions" />
        </div>
      </div>
    </div>
  </PageMain>
</template>
